import React from 'react'
import {
  Text, View, Image, ImageBackground,
} from 'react-native'
import EStyleSheet from 'react-native-extended-stylesheet'
import LinearGradientButton from '@COMPONENTS/button/LinearGradient'
import CustomerService from '@COMPONENTS/modal/CustomerService'
import Images from '@IMAGE'
import { BleConnectivityStatus, DeviceState } from '@CONSTANTS/BleConstants'
import { State } from 'react-native-ble-plx'
import { useAppSelector } from '@REDUX/store'
import AnalyticsUtil, { ANALYTICS_EVENT } from '@UTILS/AnalyticsUtil'

const errorData = {
  [State.PoweredOff]: { // 蓝牙关闭
    title: '请打开手机蓝牙',
    desc: '要将您的设备连接到手机应用程序，需要打开\n手机蓝牙',
    btnText: '连接设备',
    src: Images.home.bluetooth,
    imgText: '打开蓝牙',
    list: [],
    eventId: ANALYTICS_EVENT.tap_home_blu_not_open_connect.eventId,
  },
  treatmentAndPoweredOff: { // 治疗过程中蓝牙关闭
    title: '连接已断开，治疗仍在继续',
    desc: '要将您的设备连接到手机应用程序，需要打开\n手机蓝牙',
    btnText: '连接设备',
    src: Images.home.bluetooth,
    imgText: '打开蓝牙',
    list: [],
    eventId: ANALYTICS_EVENT.tap_in_treatment_blu_disconnected.eventId,
  },
  treatmentAndDisconnected: { // 设备连接断开
    title: '连接已断开，治疗仍在继续',
    desc: '要控制您的设备，需重新连接设备到APP',
    btnText: '连接设备',
    src: Images.home.iconOff,
    imgText: '连接已断开',
    list: [],
    eventId: ANALYTICS_EVENT.tap_in_treatment_device_disconnected.eventId,
  },
  [BleConnectivityStatus.AuthenticationFailed]: {
    title: '身份验证失败',
    desc: '该设备已关联其他账号，请连接一个新设备',
    btnText: '连接新设备',
    src: Images.home.iconOff,
    imgText: '验证失败',
    list: [],
    eventId: ANALYTICS_EVENT.tap_home_device_has_used.eventId,

  },
  [BleConnectivityStatus.ConnectionTimedOut]: { // 未找到设备
    title: '未发现纳瑞维设备',
    desc: '',
    btnText: '重新连接',
    src: Images.home.iconOff,
    imgText: '',
    list: [
      '确保纳瑞维设备是打开状态',
      '请打开手机蓝牙',
      '将纳瑞维放置在手机附近',
    ],
    eventId: ANALYTICS_EVENT.tap_home_device_not_searched.eventId,
  },
}

type ErrorState = keyof typeof errorData
interface Props {
  bleConnectivityStatus: BleConnectivityStatus | 'exhausted',
  bleState: State,
  connectDevice: (state:State, newDevice?:boolean) => void
}
const ErrorPage: React.FC<Props> = ({
  bleConnectivityStatus, bleState, connectDevice,
}) => {
  const { state: deviceState } = useAppSelector((state) => state.home.deviceData)
  let errorDataState: string = bleConnectivityStatus
  if (bleState === State.PoweredOff) {
    errorDataState = State.PoweredOff
    if (deviceState === DeviceState.Treatment) {
      // @ts-ignore
      errorDataState = 'treatmentAndPoweredOff'
    }
  }

  if (deviceState === DeviceState.Treatment && errorDataState === BleConnectivityStatus.ConnectionTimedOut) {
    // @ts-ignore
    errorDataState = 'treatmentAndDisconnected'
  }

  const errorDetail = errorData[errorDataState as ErrorState]
  const isNotFound = errorDataState === BleConnectivityStatus.ConnectionTimedOut

  console.log('ErrorState', bleConnectivityStatus)

  const onNext = () => {
    const { eventId } = errorDetail || { }
    if (eventId) {
      AnalyticsUtil.onEvent(eventId)
    }
    if (bleState === State.PoweredOff) {
      connectDevice(State.PoweredOff)
      return
    }
    if (bleConnectivityStatus === BleConnectivityStatus.ConnectionTimedOut) {
      connectDevice(State.PoweredOn)
      return
    }
    if (bleConnectivityStatus === BleConnectivityStatus.AuthenticationFailed) {
      connectDevice(State.PoweredOn, true)
    }
  }

  const customerService = () => {
    CustomerService.show()
  }
  return (
    <View style={styles.container}>
      <Text style={styles.title}>
        {errorDetail?.title}
      </Text>

      <Text style={styles.desc}>
        {errorDetail.desc}
      </Text>

      {!isNotFound && (
      <ImageBackground source={Images.home.notStart} style={styles.imageContainer}>
        <Image source={errorDetail.src} />
        <Text style={styles.errorDesc}>{errorDetail.imgText}</Text>
        {errorDetail.list.map((v, i) => (
          <View key={v} style={styles.noDeviceItem}>
            <Image source={Images.bluetoothGuide[`noDevice${i + 1}` as keyof typeof Images.bluetoothGuide]} />
            <Text style={styles.noDeviceText}>{v}</Text>
          </View>
        ))}
      </ImageBackground>
      )}

      <View style={styles.noDeviceView}>
        {errorDetail.list.map((v, i) => (
          <View key={v} style={styles.noDeviceItem}>
            <Image source={Images.bluetoothGuide[`noDevice${i + 1}` as keyof typeof Images.bluetoothGuide]} />
            <Text style={styles.noDeviceText}>{v}</Text>
          </View>
        ))}
      </View>

      <Text style={styles.customer} onPress={customerService}>
        联系客服帮助
      </Text>

      <LinearGradientButton
        style={[styles.button, styles.next]}
        onPress={onNext}
      >
        <Text style={[styles.buttonText]}>{errorDetail.btnText}</Text>
      </LinearGradientButton>
    </View>
  )
}

export default ErrorPage

const styles = EStyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '$bgColor',
    alignItems: 'center',
  },
  title: {
    fontSize: 20,
    fontFamily: 'PingFangSC-Semibold',
    color: '$fontColor',
    fontWeight: '600',
    lineHeight: 28,
    paddingTop: 48,
    textAlign: 'center',
  },
  desc: {
    paddingTop: 8,
    fontSize: 14,
    fontFamily: 'PingFangSC-Light',
    fontWeight: '300',
    color: '#595959',
    lineHeight: 22,
    textAlign: 'center',
  },
  imageContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 252,
    height: 372,
  },
  button: {
    alignSelf: 'center',
    width: 206,
    height: 49,
    borderRadius: 25,
    marginBottom: 48,
  },
  buttonText: {
    fontSize: 18,
    fontFamily: 'PingFangSC-Medium',
    fontWeight: '500',
    color: '$white',
    lineHeight: 25,
  },
  next: {
    textAlign: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorDesc: {
    fontSize: 14,
    fontFamily: 'PingFangSC-Regular',
    color: '#C2C2C2',
    lineHeight: 20,
    marginTop: 12,
  },
  customer: {
    fontSize: 14,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#8C8C8C',
    lineHeight: 20,
    marginBottom: 12,
    textAlign: 'center',
  },
  noDeviceItem: {
    flexDirection: 'row',
    paddingLeft: 50,
    paddingRight: 58,
    alignItems: 'center',
    justifyContent: 'flex-start',
    marginBottom: 12,
  },
  noDeviceText: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#595959',
    lineHeight: 24,
    marginLeft: 16,
    width: 145,
  },
  noDeviceView: {
    flex: 1,
    justifyContent: 'center',
  },
})
